package edu.uwlax.cs.oayonlinestore.client.gui.stock;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Widget;

import edu.uwlax.cs.oayonlinestore.client.OnlinestoreRService;
import edu.uwlax.cs.oayonlinestore.client.gui.Store;
import edu.uwlax.cs.oayonlinestore.client.utils.DefaultAsyncCallback;
import edu.uwlax.cs.oayonlinestore.client.utils.DekoTable;
import edu.uwlax.cs.oayonlinestore.client.utils.SwitchPage;
import edu.uwlax.cs.oayonlinestore.client.utils.Title;
import edu.uwlax.cs.oayonlinestore.client.utils.TitlePage;
import edu.uwlax.cs.oayonlinestore.vo.SubcategoryVO;

public class PageStockSubcategoryList extends TitlePage {

	int catID;

	private class SubcategoryTable extends DekoTable {

		Button delete;

		SwitchPage sp;

		public SubcategoryTable() {
			String anchor = Store.getFrame().getStockEditSubcategory()
					.getAnchor(catID, 0);
			Button add = new Button("Add Subcategory");
			add.addClickListener(sp = new SwitchPage(anchor));
			addTitle("Subcategory");
			addTitle("", 2);
			addTitleWidget(add);
		}

		public void addItem(SubcategoryVO sub) {
			String itemList = Store.getFrame().getStockItems().getAnchor(
					sub.getId());
			String editSubcat = Store.getFrame().getStockEditSubcategory()
					.getAnchor(catID, sub.getId());
			Hyperlink items = new Hyperlink("Edit items", itemList);
			Hyperlink subcat = new Hyperlink("Edit Subcategory", editSubcat);
			AddRow r = addRow();
			r.add(sub.getTitle());
			r.add(items);
			r.add(subcat);
			r.add(delete = new Button("Delete"));
			delete.addClickListener(new ButtonClickListener(sub));
		}

		public class ButtonClickListener implements ClickListener {
			SubcategoryVO co = null;

			public ButtonClickListener(SubcategoryVO c) {
				co = c;
			}

			public void onClick(Widget arg0) {

				OnlinestoreRService.Util.getInstance().disableSubcategory(
						co.getId(), new DoneAddAsycHandler());
			}
		}

		public class DoneAddAsycHandler extends DefaultAsyncCallback {

			public void onSuccess(Object o) {
				onShow(catID);
			}
		}

	}

	SubcategoryTable table;

	protected void create() {
		setTitle("Subcategories");
	}

	public boolean onShow(int param) {
		catID = param;
		removeAll();
		add(new Title("Subcategories"));
		add(table = new SubcategoryTable());
		OnlinestoreRService.Util.getInstance().getSubcategories(param,
				getAsyncHandler());
		return true;
	}

	protected void onDataArrived(Object o) {
		SubcategoryVO[] subs = (SubcategoryVO[]) o;
		for (int i = 0; i < subs.length; i++)
			table.addItem(subs[i]);

	}

	public String getID() {
		return "ListSubcategories";
	}

}
